package slu.appli.wodtimer.swing2.logger;

import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

import slu.appli.logger.interfaces.LoggerInterface;
import slu.appli.wodtimer.swing2.XComponentFactoryInterface;
import slu.appli.wodtimer.swing2.cst.Text4ComponentCst;

public class XTextLogger
extends JScrollPane
implements LoggerInterface, XComponentFactoryInterface {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private final JTextArea txt;
	private static final String EMPTY = "";

	public XTextLogger() {
		super();
		this.txt = new JTextArea();
		this.txt.setLineWrap(true);
		this.txt.setFocusable(false);
		this.txt.setEditable(false);
		this.setViewportView(this.txt);
		this.txt.setText(Text4ComponentCst.TXT_HELLO);
	}

	public void addComment(String string) {
		if (SwingUtilities.isEventDispatchThread()) {
			if (EMPTY.equals(this.txt.getText())) {
				this.txt.setText(string);
			}
			else {
				this.txt.setText(this.txt.getText() + "\n" + string);
			}
		}
		else {
			SwingUtilities.invokeLater(new AddCommentSwingTask(string));
		}
	}
	
	private class AddCommentSwingTask implements Runnable {
		private final String string;
		
		public AddCommentSwingTask(final String string) {
			super();
			this.string = string;
		}

		public void run() {
			XTextLogger.this.addComment(this.string);
		}
	}

	public void addException(Exception e) {
		StringBuilder s = new StringBuilder(e.toString());
		Throwable t = e.getCause();
		int count = 0;
		while (t != null) {
			s.append("\n");
			s.append(t.toString());
			t = e.getCause();
			count++;
			if (count > 15) {
				s.append("\n...");
				break;
			}
		}
		this.addComment(s.toString());
	}

	public void clear() {
		this.txt.setText(EMPTY);
	}

	@Override
	public JComponent getComponent() {
		return this;
	}

}
